import React, { Component } from 'react';
import {
	View, Text, StyleSheet, TouchableOpacity, Image, TextInput,
	PixelRatio, Platform, Keyboard, DeviceEventEmitter
} from 'react-native';

import { GLOBAL } from '../../../config/global';
import { style } from '../../../theme/style';
import { MapView, MapTypes, Geolocation } from 'react-native-baidu-map';
import { PageStatusIndex } from '../../../component/page-status/PageStatusIndex';

const scale = GLOBAL.SCALE;

let curAddress = '';

export class AddressOptionPage extends Component {

	static navigationOptions = ({ navigation }) => {
		const params = navigation.state.params || {};
		const curCity = params.curCity;
		const { selectAddress } = params;
		if (selectAddress) {
			selectAddress.latitude = selectAddress.latitude;
			selectAddress.longitude = selectAddress.longitude;
			params.setSelectAddress(selectAddress);
		}

		const searchIcon = require('../../../imgs/global/whiteSearch.png');
		const searchIconStyle = { width: 26 * scale, resizeMode: 'contain', marginRight: 10 * scale }

		return {
			headerTitle: '请选择地址',
			headerStyle: {
				backgroundColor: style.color.themeColor,
			},
			headerTintColor: '#fff',
			headerRight: <TouchableOpacity onPress={() => {
				params.goToAddressList();
			}} activeOpacity={0.5}><Image source={searchIcon} style={searchIconStyle} /></TouchableOpacity>
		};
	};

	componentWillMount () {
		this.keyboardDidShowListener = Keyboard.addListener('keyboardDidShow', this._keyboardDidShow.bind(this));
		this.keyboardDidHideListener = Keyboard.addListener('keyboardDidHide', this._keyboardDidHide.bind(this));

		DeviceEventEmitter.addListener('CheckAddressItem', (dic) => {
			const { params } = this.props.navigation.state;
			//接收到前一页发送的通知，刷新数据，刷新UI
			if (params.selectAddress) {
				this.getReverseGeoCodeResult(Number(params.selectAddress.latitude), Number(params.selectAddress.longitude), params.selectAddress.name);
			}
		});
	}

	componentWillUnmount () {
		try {
			this.keyboardDidShowListener.remove();
			this.keyboardDidHideListener.remove();
		} catch (error) {
			console.log(error);
		}
	}

	_keyboardDidShow () {
		this.setState({ keyboard: true });
	}

	_keyboardDidHide () {
		this.setState({ keyboard: false });
	}

	componentDidMount () { // 获取位置
		const { addressObj } = this.props.navigation.state.params;

		if (addressObj && addressObj.latitude) {
			addressObj.latitude = addressObj.latitude;
			addressObj.longitude = addressObj.longitude;
			this._setSelectAddress(addressObj);
		} else {
			this.getCurrentPosition();
		}

		this.props.navigation.setParams({
			setSelectAddress: this._setSelectAddress,
			goToAddressList: this.goToAddressList,
		});
	}

	_setSelectAddress (selectAddress) {
		const { createNew } = this.props.navigation.state.params;
		this.addressObj = selectAddress;
		const { longitude, latitude, city, district, poiInfo, name, address } = selectAddress;
		console.log(101, selectAddress)
		this.addressCodeParam = selectAddress;
		curAddress = poiInfo;
		curCity = city;
		this.setState({
			pageStatus: {
				status: 'data'
			},
			zoom: 18,
			markers: [{
				latitude: Number(latitude),
				longitude: Number(longitude),
				address: address,
				city: city,
				district: district,
				title: '位置:' + poiInfo,
				poiInfo: createNew ? '' : name ? name : poiInfo
			}],
			center: {
				latitude: Number(latitude),
				longitude: Number(longitude),
			},
		});
		if (latitude && longitude) {
			this.getReverseGeoCodeResult(Number(latitude), Number(longitude), name ? name : poiInfo);
		}
	}

	//获取地理位置
	getCurrentPosition () {
		Geolocation.getCurrentPosition().then(
			(data) => {
				console.log("getCurrentPosition:" + JSON.stringify(data));
				this.setState({
					pageStatus: {
						status: 'data'
					},
					zoom: 18,
					markers: [{
						latitude: data.latitude,
						longitude: data.longitude,
						province: data.province,
						city: data.city,
						district: data.district,
						address: data.address,
						title: '位置:' + data.address,
						poiInfo: data.poiInfo,
					}],
					center: {
						latitude: data.latitude,
						longitude: data.longitude
					},
				});
				this.addressCodeParam = {
					latitude: data.latitude,
					longitude: data.longitude,
					province: data.province,
					city: data.city,
					district: data.district,
					address: data.address,
					poiInfo: data.poiInfo,
				}
				console.log(150, data);
				curCity = data.city;
				curAddress = data.poiInfo;
				/* this.props.navigation.setParams({
					curCity
				}); */
			}
		).catch(error => {
			this.setState({
				pageStatus: {
					status: 'error',
					onErrorPress: () => {
						this.setState({
							pageStatus: {
								status: 'loading'
							}
						})
						this.getCurrentPosition();
					}
				},
			})
			console.log(error, 'error')
		})
	}

	// 经纬度位置转换具体地址
	getReverseGeoCodeResult (latitude, longitude, listItem) {
		Geolocation.reverseGeoCode(latitude, longitude, listItem).then(
			(data) => {
				console.log("getReverseGeoCodeResult:" + JSON.stringify(data));
				this.setState({
					pageStatus: {
						status: 'data'
					},
					zoom: 18,
					markers: [{
						latitude: latitude,
						longitude: longitude,
						province: data.province,
						city: data.city,
						district: data.district,
						poiInfo: listItem ? listItem : data.poiInfo,
						address: data.address,
						title: '位置:' + data.address
					}],
					center: {
						latitude: latitude,
						longitude: longitude
					},
				});
				this.addressCodeParam = {
					latitude: latitude,
					longitude: longitude,
					province: data.province,
					city: data.city,
					district: data.district,
					address: data.address,
					poiInfo: listItem ? listItem : data.poiInfo,
				}
				curAddress = data.poiInfo;
			}
		).catch(error => {
			this.setState({
				pageStatus: {
					status: 'error',
					onErrorPress: () => {
						this.setState({
							pageStatus: {
								status: 'loading'
							}
						})
						this.getReverseGeoCodeResult(Number(latitude), Number(longitude), listItem);
					}
				},
			})
			console.log(error, 'error')
		})
	}

	constructor(props) {
		super(props);
		this.state = {
			pageStatus: {
				status: 'loading'
			},
			mayType: MapTypes.NORMAL,
			zoom: 15,
			trafficEnabled: false,
			baiduHeatMapEnabled: false,
			keyboard: false,
			markers: [],
			center: {},
		};
		this.addressCodeParam = {}

		this._setSelectAddress = this._setSelectAddress.bind(this);
		this.goToAddressList = this.goToAddressList.bind(this);

		this.addressObj = {};
		this.goBackPage = this.props.navigation.state.params.goBackPage;
	}

	goToAddressList () {
		const curAddressStr = (this.addressCodeParam.poiInfo) ? this.addressCodeParam.poiInfo : curAddress
		this.props.navigation.navigate("AddressListPage", {
			curCity: this.addressCodeParam.city,
			curAddress: curAddressStr,
			addressObj: this.addressObj
		})
	}

	render () {
		const { params } = this.props.navigation.state;
		const { markers, pageStatus, keyboard } = this.state;
		const inputsCellTop = { bottom: Platform.OS === 'ios' ? (keyboard ? 250 * scale : 5 * scale) : 5 * scale };

		return (
			<View style={styles.container}>
				{
					pageStatus.status === 'data' ? (
						<View style={styles.container}>
							<MapView
								trafficEnabled={this.state.trafficEnabled}
								baiduHeatMapEnabled={this.state.baiduHeatMapEnabled}
								zoom={this.state.zoom}
								mapType={this.state.mapType}
								center={this.state.center}
								markers={this.state.markers}
								style={styles.map}
								onMarkerClick={(e) => {
									console.log('markerlick', e);
								}}
								onMarkerDragEnd={(e) => {
									console.log('drag', e);
									this.getReverseGeoCodeResult(e.position.latitude, e.position.longitude);
								}}
								onMapStatusChangeFinish={(e) => {
									console.log('change', e);
									this.getReverseGeoCodeResult(e.target.latitude, e.target.longitude);
								}}
								onMapClick={(e) => {//支持地图点击的时候切换改变地址
									console.log('click', e);
									this.getReverseGeoCodeResult(e.latitude, e.longitude);
								}}
							>
							</MapView>

							<View style={styles.location}>
								<TouchableOpacity style={styles.mapSelect}
									activeOpacity={0.5} onPress={() => { this.getCurrentPosition(); }}>
									<Image style={styles.locationIcon} source={require('../../../imgs/global/location.png')} />
								</TouchableOpacity>
							</View>
							<View style={[styles.mapInputContainer, inputsCellTop]}>
								<View style={styles.infoRow}>
									<TouchableOpacity style={styles.mapSelect}
										activeOpacity={0.5} onPress={() => {
											this.goToAddressList();
										}}>
										<View style={styles.infoRowLeft}><Image style={styles.iconLeft} source={require('../../../imgs/global/position.png')} /></View>
										<View style={styles.infoCenter}><Text style={styles.infoCenterText}>{markers[0].address || '请选择'}</Text></View>
										<View style={styles.infoRowRight}><Image style={styles.iconRight} source={require('../../../imgs/arrow-left.png')} /></View>
									</TouchableOpacity>
								</View>
								<View style={styles.infoRow}>
									<TextInput
										ref="address"
										style={styles.textInput}
										underlineColorAndroid='transparent'
										maxLength={30}
										defaultValue={markers[0].poiInfo}
										placeholder={'请输入详细地址'}
										onChangeText={(txt) => {
											this.addressCodeParam.poiInfo = txt;
											// this._setSelectAddress(this.addressCodeParam)
										}}
									/>
								</View>
								<View style={styles.submitBtnCell}>
									<TouchableOpacity activeOpacity={0.5} style={styles.submitBtn}
										onPress={() => {
											if (this.goBackPage && this.goBackPage.length) {
												console.log(365, this.addressCodeParam)
												this.props.navigation.navigate(this.goBackPage, {
													addressCodeParam: this.addressCodeParam,
												})
											}
										}} >
										<Text style={styles.submitBtnText}>确定</Text>
									</TouchableOpacity>
								</View>
							</View>
						</View>) : (<PageStatusIndex {...pageStatus} />)   //页面加载状态
				}

			</View>
		);
	}

}

const styles = StyleSheet.create({
	container: {
		flex: 1,
		flexDirection: 'row',
		justifyContent: 'flex-start',
	},
	map: {
		flex: 1,
	},
	location: {
		flex: 1,
		position: 'absolute',
		right: 6 * scale,
		bottom: 185 * scale,
	},
	mapInputContainer: {
		backgroundColor: '#fff',
		width: 365 * scale,
		position: 'absolute',
		left: 5 * scale,
		bottom: 8 * scale,
	},
	infoRow: {
		width: 365 * scale,
		height: 52 * scale,
		marginLeft: 5 * scale,
		paddingRight: 5 * scale,
		borderBottomColor: '#e4e4e4',
		borderBottomWidth: 1 / PixelRatio.get(),
		flexDirection: 'row',
		alignItems: 'center',
		flexWrap: 'wrap'
	},
	mapSelect: {
		flex: 1,
		flexDirection: 'row',
	},
	infoRowLeft: {
		justifyContent: 'center',
		height: 52 * scale,
		marginLeft: 6 * scale,
	},
	infoCenter: {
		justifyContent: 'center',
		height: 52 * scale,
		flex: 1
	},
	infoCenterText: {
		fontSize: 13 * scale,
		color: '#404040',
	},
	infoRowRight: {
		justifyContent: 'center',
		height: 52 * scale,
	},
	iconLeft: {
		height: 16 * scale,
		width: 10 * scale,
		marginRight: 5 * scale,
	},
	iconRight: {
		height: 12 * scale,
		width: 6 * scale,
		marginRight: 5 * scale,
	},
	textInput: {
		borderWidth: 0,
		fontSize: 13 * scale,
		color: '#8B8B8B',
		width: '100%',
		height: 18 * scale,
		padding: 0,
		marginLeft: 18 * scale,
	},
	submitBtnCell: {
		width: '100%',
		justifyContent: 'center',
		alignItems: 'center',
		marginTop: 10 * scale,
		marginBottom: 10 * scale,
	},
	submitBtn: {
		justifyContent: 'center',
		alignItems: 'center',
		width: '94%',
		height: 44 * scale,
		borderRadius: 100,
		backgroundColor: style.color.themeColor,
	},
	submitBtnText: {
		color: '#fff',
		fontSize: 18 * scale,
	},
})